import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { ModelConfigInfo, ModelTemplate, ModelTestResult, ConfigEvent } from '@/types/model-config';
import modelConfigService from '@/services/model-config.service';
import configSyncService from '@/services/config-sync.service';
// import apiKeyService from '@/services/api-key.service'; // 后端/keys端点未实现，暂时禁用

interface ModelConfigState {
  // 状态
  configs: ModelConfigInfo[];
  templates: ModelTemplate[];
  loading: boolean;
  error: string | null;
  testingConfigs: Set<string>;
  syncStatus: {
    syncing: boolean;
    lastSyncTime?: Date;
    pendingChanges: number;
  };
  
  // 操作
  loadConfigs: () => Promise<void>;
  loadTemplates: () => Promise<void>;
  createConfig: (config: any) => Promise<void>;
  updateConfig: (id: string, config: any) => Promise<void>;
  deleteConfig: (id: string) => Promise<void>;
  testConnection: (config: {baseUrl: string; apiKey: string; modelName?: string}) => Promise<ModelTestResult>;
  refreshConfigStatus: (configId: string) => Promise<void>;
  batchRefreshStatus: () => Promise<void>;
  exportConfigs: () => Promise<string>;
  importConfigs: (configData: string) => Promise<string | void>;
  
  // 同步操作
  startSync: () => void;
  stopSync: () => void;
  forceSync: () => Promise<void>;
  handleConfigChange: (event: ConfigEvent) => void;
  
  // UI状态
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
}

export const useModelConfigStore = create<ModelConfigState>()(
  persist(
    (set, get) => ({
      // 初始状态
      configs: [],
      templates: [],
      loading: false,
      error: null,
      testingConfigs: new Set(),
      syncStatus: {
        syncing: false,
        pendingChanges: 0
      },

      // 加载配置列表
      loadConfigs: async () => {
        console.log('🔄 [Store] loadConfigs 开始执行...');
        set({ loading: true, error: null });

        try {
          // 直接从service获取配置（包含API → localStorage → 默认配置的fallback链）
          console.log('📡 [Store] 调用 modelConfigService.getModelConfigs()...');
          let configs = await modelConfigService.getModelConfigs();

          console.log('📦 [Store] 获取到配置:', {
            count: configs.length,
            configs: configs.map(c => ({
              id: c.id,
              name: c.displayName || c.modelName,
              isActive: c.isActive,
              status: c.status,
              provider: c.providerId
            }))
          });

          // 如果成功获取到配置（包括默认配置），尝试同步密钥信息
          // 注意：后端/keys端点未实现，暂时禁用密钥同步功能
          // if (configs.length > 0) {
          //   try {
          //     configs = await apiKeyService.syncKeysToConfigs(configs);
          //     console.log('✅ 从API/缓存/默认配置加载了', configs.length, '个模型配置');
          //   } catch (syncError) {
          //     // 同步失败不影响配置加载，继续使用原配置
          //     console.warn('⚠️ 密钥同步失败，使用原配置:', syncError);
          //   }
          // }

          console.log('✅ 从API/缓存/默认配置加载了', configs.length, '个模型配置');

          set({ configs, loading: false });

          // 启动同步服务
          if (configs.length > 0) {
            get().startSync();
          }
        } catch (error) {
          console.error('❌ Failed to load configs:', error);
          // 最后的兜底：即使出错也尝试从localStorage获取
          const { configs: cachedConfigs } = get();
          if (cachedConfigs && cachedConfigs.length > 0) {
            console.log('🔄 使用localStorage缓存的配置');
            set({ configs: cachedConfigs, loading: false });
          } else {
            set({
              error: error instanceof Error ? error.message : '加载配置失败',
              loading: false,
              configs: [] // 确保不是undefined
            });
          }
        }
      },

      // 加载模板
      loadTemplates: async () => {
        try {
          const templates = await modelConfigService.getModelTemplates();
          set({ templates });
        } catch (error) {
          console.error('Failed to load templates:', error);
          set({ error: error instanceof Error ? error.message : '加载模板失败' });
        }
      },

      // 创建配置
      createConfig: async (configData) => {
        console.log('[STORE] createConfig called with:', configData);
        set({ loading: true, error: null });
        
        try {
          const newConfig = await modelConfigService.createModelConfig(configData);
          console.log('[STORE] Config created successfully:', newConfig);
          const { configs } = get();
          set({ 
            configs: [...configs, newConfig],
            loading: false 
          });
          
          // 发布配置变化事件
          configSyncService.triggerConfigChange({
            type: 'created',
            configId: newConfig.id,
            timestamp: new Date(),
            changes: newConfig
          });
        } catch (error) {
          console.error('Failed to create config:', error);
          set({ 
            error: error instanceof Error ? error.message : '创建配置失败',
            loading: false 
          });
          throw error;
        }
      },

      // 更新配置
      updateConfig: async (id, configData) => {
        set({ loading: true, error: null });
        
        try {
          const updatedConfig = await modelConfigService.updateModelConfig(id, configData);
          const { configs } = get();
          set({
            configs: configs.map(config => 
              config.id === id ? updatedConfig : config
            ),
            loading: false
          });
          
          // 发布配置变化事件
          configSyncService.triggerConfigChange({
            type: 'updated',
            configId: id,
            timestamp: new Date(),
            changes: configData
          });
        } catch (error) {
          console.error('Failed to update config:', error);
          set({ 
            error: error instanceof Error ? error.message : '更新配置失败',
            loading: false 
          });
          throw error;
        }
      },

      // 删除配置
      deleteConfig: async (id) => {
        set({ loading: true, error: null });
        
        try {
          await modelConfigService.deleteModelConfig(id);
          const { configs } = get();
          set({
            configs: configs.filter(config => config.id !== id),
            loading: false
          });
          
          // 发布配置变化事件
          configSyncService.triggerConfigChange({
            type: 'deleted',
            configId: id,
            timestamp: new Date()
          });
        } catch (error) {
          console.error('Failed to delete config:', error);
          set({ 
            error: error instanceof Error ? error.message : '删除配置失败',
            loading: false 
          });
          throw error;
        }
      },

      // 测试连接
      testConnection: async (config) => {
        const { testingConfigs } = get();
        const testKey = `${config.baseUrl}-${config.modelName || 'test'}`;
        
        set({ 
          testingConfigs: new Set([...testingConfigs, testKey]),
          error: null 
        });
        
        try {
          const result = await modelConfigService.testModelConnection(config);
          const newTestingConfigs = new Set(testingConfigs);
          newTestingConfigs.delete(testKey);
          set({ testingConfigs: newTestingConfigs });
          return result;
        } catch (error) {
          const newTestingConfigs = new Set(testingConfigs);
          newTestingConfigs.delete(testKey);
          set({ 
            testingConfigs: newTestingConfigs,
            error: error instanceof Error ? error.message : '连接测试失败'
          });
          throw error;
        }
      },

      // 刷新单个配置状态（自动健康检查）
      refreshConfigStatus: async (configId) => {
        const { configs, testingConfigs } = get();
        const config = configs.find(c => c.id === configId);
        
        if (!config) return;
        
        set({ 
          testingConfigs: new Set([...testingConfigs, configId])
        });
        
        try {
          // 使用新的健康检查接口，不需要传递API key
          const result = await modelConfigService.checkModelHealth(configId);
          
          const newTestingConfigs = new Set(testingConfigs);
          newTestingConfigs.delete(configId);
          
          // 更新本地状态
          const updatedConfig = { 
            ...config, 
            status: result.status,
            lastChecked: new Date()
          };
          
          set({
            configs: configs.map(c => 
              c.id === configId ? updatedConfig : c
            ),
            testingConfigs: newTestingConfigs
          });
          
          console.log(`[Health Check] 完成: ${config.displayName || config.modelName} - ${result.status}`);
        } catch (error) {
          const newTestingConfigs = new Set(testingConfigs);
          newTestingConfigs.delete(configId);
          
          // 更新本地状态为不健康
          const updatedConfig = { 
            ...config, 
            status: 'unhealthy' as const,
            lastChecked: new Date()
          };
          
          set({
            configs: configs.map(c => 
              c.id === configId ? updatedConfig : c
            ),
            testingConfigs: newTestingConfigs
          });
          
          console.error(`[Health Check] 失败: ${config.displayName || config.modelName}`, error);
        }
      },

      // 批量刷新状态
      batchRefreshStatus: async () => {
        const { configs } = get();
        const activeConfigs = configs.filter(c => c.isActive);
        
        if (activeConfigs.length === 0) return;
        
        set({ loading: true });
        
        try {
          const configIds = activeConfigs.map(c => c.id);
          const results = await modelConfigService.batchTestModelHealth(configIds);
          
          set({
            configs: configs.map(config => {
              const result = results[config.id];
              return result 
                ? { 
                    ...config, 
                    status: result.status,
                    lastChecked: new Date()
                  }
                : config;
            }),
            loading: false
          });
        } catch (error) {
          console.error('Failed to batch refresh status:', error);
          set({ 
            error: error instanceof Error ? error.message : '批量刷新失败',
            loading: false 
          });
        }
      },

      // 导入导出功能
      exportConfigs: async () => {
        const { configs } = get();
        return JSON.stringify(configs, null, 2);
      },

      importConfigs: async (configData: string) => {
        try {
          const importedConfigs = JSON.parse(configData);
          if (!Array.isArray(importedConfigs)) {
            throw new Error('配置数据格式错误：必须是数组格式');
          }
          
          const { configs: existingConfigs } = get();
          const newConfigs = [...existingConfigs];
          let importCount = 0;
          let updateCount = 0;
          
          for (const config of importedConfigs) {
            // 验证必要字段
            if (!config.providerId || !config.modelName) {
              console.warn('跳过无效配置：', config);
              continue;
            }
            
            const existingIndex = newConfigs.findIndex(c => 
              c.providerId === config.providerId && c.modelName === config.modelName
            );
            
            if (existingIndex >= 0) {
              // 更新现有配置
              newConfigs[existingIndex] = { 
                ...config, 
                id: newConfigs[existingIndex].id,
                updatedAt: new Date()
              };
              updateCount++;
            } else {
              // 添加新配置
              newConfigs.push({ 
                ...config, 
                id: `imported-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
                createdAt: new Date(),
                updatedAt: new Date()
              });
              importCount++;
            }
          }
          
          set({ configs: newConfigs });
          
          const message = [];
          if (importCount > 0) message.push(`新增 ${importCount} 个配置`);
          if (updateCount > 0) message.push(`更新 ${updateCount} 个配置`);
          
          return message.join('，') || '没有有效的配置被导入';
        } catch (error) {
          console.error('Import failed:', error);
          throw new Error(error instanceof Error ? error.message : '导入失败');
        }
      },

      // 同步操作
      startSync: () => {
        // 启动同步服务
        configSyncService.startSync();
        
        // 监听配置变化
        configSyncService.onConfigChange((event) => {
          get().handleConfigChange(event);
        });
        
        // 监听同步状态
        configSyncService.on('sync-start', () => {
          set({ syncStatus: { ...get().syncStatus, syncing: true } });
        });
        
        configSyncService.on('sync-complete', () => {
          set({ 
            syncStatus: { 
              syncing: false, 
              lastSyncTime: new Date(),
              pendingChanges: 0 
            } 
          });
        });
      },
      
      stopSync: () => {
        configSyncService.stopSync();
      },
      
      forceSync: async () => {
        await configSyncService.forceSync();
      },
      
      handleConfigChange: (event: ConfigEvent) => {
        const { configs } = get();
        
        switch (event.type) {
          case 'created':
            if (event.changes && !configs.find(c => c.id === event.configId)) {
              set({ configs: [...configs, event.changes as ModelConfigInfo] });
            }
            break;
            
          case 'updated':
            if (event.changes) {
              set({
                configs: configs.map(config => 
                  config.id === event.configId 
                    ? { ...config, ...event.changes }
                    : config
                )
              });
            }
            break;
            
          case 'deleted':
            set({
              configs: configs.filter(config => config.id !== event.configId)
            });
            break;
        }
      },

      // UI状态管理
      setLoading: (loading) => set({ loading }),
      setError: (error) => set({ error }),
      clearError: () => set({ error: null })
    }),
    {
      name: 'model-config-storage',
      version: 2, // 增加版本号，强制清除旧缓存
      partialize: (state) => ({
        configs: state.configs,
        templates: state.templates
      }),
      // 迁移函数：版本升级时清除旧数据
      migrate: (persistedState: any, version: number) => {
        console.log('🔄 [Store] 缓存迁移: 版本', version, '-> 2');
        if (version < 2) {
          // 版本低于2时，清除所有数据，强制重新加载
          console.log('⚠️ [Store] 清除旧版本缓存，强制从API重新加载');
          return {
            configs: [],
            templates: []
          };
        }
        return persistedState;
      }
    }
  )
);